package br.com.quixada.smtpredes.servidor;


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {
	
	private String mailSMTPServer; 		
	private String mailSMTPServerPort;
	
	public SendMail(String mailSMTPServer, String mailSMTPServerPort) {
		this.mailSMTPServer = mailSMTPServer;
		this.mailSMTPServerPort = mailSMTPServerPort;
	}
	
	public void sendMail(String de, String[] destinatarios, String assunto, StringBuffer mensagem) throws MessagingException {
	
		Properties prop = new Properties();
		
		prop.put("mail.transport.protocol", "smtp");
		prop.put("mail.smtp.starttls.enable", "true");
		prop.put("mail.smtp.host", mailSMTPServer);
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.smtp.user", de);
		prop.put("mail.debug", "true");
		prop.put("mail.smtp.port", mailSMTPServerPort);
		prop.put("mail.smtp.socketFactory.port", mailSMTPServerPort);
		prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		prop.put("mail.smtp.socketFactory.fallback", "false");

		SimpleAuth autent = new SimpleAuth("user", "password");
		
		Session sessao = Session.getDefaultInstance(prop,autent);
		sessao.setDebug(true);
		
		Message message = new MimeMessage(sessao);
		
		InternetAddress from = new InternetAddress (de);
		message.setFrom(from);
		
		int arrayLength = destinatarios.length;
		InternetAddress[] emailDestino = new InternetAddress[arrayLength];
		for (int i = 0; i < arrayLength; i++) {
			emailDestino[i] = new InternetAddress (destinatarios[i]);
		}
		message.setRecipients( Message.RecipientType.TO, emailDestino);
		
		message.setSubject(assunto);
		
		MimeMultipart mpRoot = new MimeMultipart("mixed");
		MimeMultipart mpContent = new MimeMultipart("alternative");
		MimeBodyPart contentPartRoot = new MimeBodyPart();
		contentPartRoot.setContent(mpContent);
		mpRoot.addBodyPart(contentPartRoot);
		
		MimeBodyPart mbp2 = new MimeBodyPart();
		mbp2.setContent("<P>" + mensagem.toString() + "</P>", "text/html");
		mpContent.addBodyPart (mbp2);
		
		message.setContent(mpRoot);
		message.saveChanges();
		
		Transport.send(message);
	}
}